/**
 * Main document logic.
 */
$(document).ready(function () {
    /*$('body').shortcuts();*/

    var shortcutsData = {};
    var shortcutsVisible = false;
    $('#showList').click(function () {
        var results = handleList(shortcutsData, shortcutsVisible);
        shortcutsData = results[0];
        shortcutsVisible = results[1];
    });

    // Click on "Add shortcut" button
    $('#addShortcut').click(function () {
        saveShortcuts(getNewShortcut()); // Save items locally
    });

    // TODO: Click on "Edit" button
    $('.btn-info').click(function(){

    });

    // Repair shortcuts
    $('#repairShortcutStorage').click(function(){
       repairShortcuts();
    });
});

/**
 * ==================================
 * Functions part
 * ==================================
 */

    function handleList(shortcutsData,shortcutsVisible) {
        if ($.isEmptyObject(shortcutsData)) {
            shortcutsData = getShortcuts();
        }
        if (!shortcutsVisible) {
            if ($('#allStoredShortcuts').html().length == 0 ) {
                $('#allStoredShortcuts').append(shortcutsData).show();
            } else {
                $('#allStoredShortcuts').show();
            }

            shortcutsVisible = true;
        } else {
            $('#allStoredShortcuts').hide();
            shortcutsVisible = false;
        }
        return [shortcutsData, shortcutsVisible]
    }

    /**
     * Returns object from new shortcut inputs
     * @returns {{url: (*|jQuery), shortcut: (*|jQuery)}}
     */
    function getNewShortcut() {
        return  {
            "url": $('#url').val(),
            "shortcut": $('#shortcut').val()
        };
    }

    /**
     * Function saves items object to local storage.
     * @param newShortcut
     */
    function saveShortcuts(newShortcut) {
        var shortcuts = (localStorage.shortcuts) ? JSON.parse(localStorage.shortcuts) : {};

        if ($(shortcuts[0]).size() == 0) {
            shortcuts = {
                0: newShortcut
            }
        } else {
            shortcuts[Object.keys(shortcuts).length] = newShortcut;
        }

        localStorage.shortcuts = JSON.stringify(shortcuts);
        location.reload();
    }

    /**
     * Helper function to fill template
     *
     * @param values
     * @param template
     * @returns {*}
     */
    function fillTemplate(values, template) {
        $.each(values, function (key) {
            var re = new RegExp('{{' + key + '}}','g');
            template = template.replace(re, values[key]);
        });
        return template;
    }

    /**
     * Function get shortcuts from localstorage & display them.
     */
    function getShortcuts() {
        var shortcuts = (localStorage.shortcuts) ? JSON.parse(localStorage.shortcuts) : {};
        var returnValue = '';
        var rowTemplate =
            '<div class="row-{{key}} clearfix form-group col-xs-12">' +
                '<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"> {{shortcut}} </div> ' +
                '<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5"> {{shortcut-url}}</div>' +
                '<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 text-center delete">' +
                '<span class="glyphicon glyphicon-trash delete-{{key}} btn btn-danger pull-right"></span>' +
                '</div>' +
                '<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 text-center">' +
                '<span class="glyphicon glyphicon-pencil edit-{{key}} btn btn-info pull-right"></span>' +
                '</div>' +
                '</div> ';


        $.each(shortcuts, function (key, value) {
            var values = {
                'shortcut': value['shortcut'],
                'shortcut-url': value['url'],
                'key': key
            };

            /*$(storedShortcutsContainer).append(
                fillTemplate(values, rowTemplate)
            );*/
            returnValue += fillTemplate(values, rowTemplate);
        });

        return returnValue;
    }

    /**
     * Function deletes shortcut from local storage.
     * TODO: Not working yet !!!
     * @param object
     */
    function deleteShortcut(object) {
        var className = $(object).find('span').attr('class').split('delete-');
        var shortcutId = className[1];
        var shortcuts = JSON.parse(localStorage.shortcuts);
        delete shortcuts[shortcutId];
        shortcuts = $.map(shortcuts, function (value, key) {
            return value;
        });
        localStorage.shortcuts = JSON.stringify(shortcuts);
        location.reload();
    }